<template>
  <el-form
    label-position="right"
    label-width="100px"
    class="form-card"
    :model="localForm"
    :rules="rules"
    ref="memberCardForm"
  >
    <div class="form-top">
      <!-- 课时卡名称 下拉框 -->
      <el-form-item label="课时卡名称" prop="cardName">
        <el-select
          v-model="localForm.cardName"
          placeholder="请选择课时卡名称"
          filterable
          clearable
          @change="onCardNameChange"
        >
          <el-option
            v-for="item in cardNameOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 课时卡类型 自动填充 -->
      <el-form-item label="课时卡类型">
        <el-input v-model="localForm.type" disabled placeholder="自动识别" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="localForm.price" style="width: 80%">
          <template #prepend>￥</template>
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="描述信息" prop="description">
        <el-input type="textarea" v-model="localForm.description" />
      </el-form-item>

      <el-form-item label="备注信息" prop="note">
        <el-input type="textarea" v-model="localForm.note" />
      </el-form-item>
    </div>

    <div class="form-top">
      <el-form-item label="总课时" prop="totalClasses">
        <el-input
          type="number"
          min="0"
          placeholder="总课时"
          class="w50"
          v-model.number="localForm.totalClasses"
        />
      </el-form-item>

      <el-form-item label="剩余课时" prop="remainingClasses">
        <el-input
          type="number"
          min="0"
          placeholder="剩余课时"
          class="w50"
          v-model.number="localForm.remainingClasses"
        />
      </el-form-item>

      <!-- 支持课程表格 -->
      <el-form-item label="支持课程">
        <el-table :data="filteredCourses" size="small" style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" />
          <el-table-column prop="level" label="等级" />
          <el-table-column prop="classroom" label="教室" />
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveMemberCard">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  memberCardFormData: Object,
  addEditDrawer: Boolean,
  drawerTitle: String,
})
const emit = defineEmits(['update:addEditDrawer', 'saved'])

const localForm = reactive({
  id: null,
  cardName: '',
  type: '',
  price: '',
  totalClasses: 0,
  remainingClasses: 0,
  description: '',
  note: ''
})

const rules = {
  cardName: [{ required: true, message: '请选择课时卡名称', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  totalClasses: [{ type: 'number', min: 0, message: '请输入总课时', trigger: 'blur' }],
  remainingClasses: [{ type: 'number', min: 0, message: '请输入剩余课时', trigger: 'blur' }]
}

const cardNameOptions = [
  'Scratch初级班-20课时卡',
  'Scratch中级班-24课时卡',
  'Scratch高级班-32课时卡',
  'Python基础班-32课时卡',
  'Python进阶班-48课时卡'
]

const allCourses = ref([])
const filteredCourses = ref([])

const courseMapping = {
  'Scratch初级班': ['SC101', 'SC102', 'SC103', 'SC104', 'SC105'],
  'Scratch中级班': ['SC201', 'SC202', 'SC203', 'SC204'],
  'Scratch高级班': ['SC301', 'SC302', 'SC303'],
  'Python基础班': ['PY101', 'PY102', 'PY103', 'PY104'],
  'Python进阶班': ['PY201', 'PY202', 'PY203', 'PY204']
}

const getCardLevel = (name) => {
  if (!name) return ''
  if (name.includes('初级')) return '初级卡'
  if (name.includes('中级')) return '中级卡'
  if (name.includes('高级')) return '高级卡'
  if (name.includes('进阶')) return '进阶卡'
  if (name.includes('体验')) return '体验卡'
  if (name.includes('特惠')) return '特惠卡'
  if (name.includes('基础')) return '基础卡'
  return '普通卡'
}

const onCardNameChange = () => {
  localForm.type = getCardLevel(localForm.cardName)
  filterCourses()
}

const filterCourses = () => {
  const matchedKey = Object.keys(courseMapping).find(key => localForm.cardName.includes(key))
  if (!matchedKey) {
    filteredCourses.value = []
    return
  }
  const courseIds = courseMapping[matchedKey]
  filteredCourses.value = allCourses.value.filter(c => courseIds.includes(c.courseId))
}

const fetchCourses = async () => {
  try {
    const res = await axios.get('http://localhost:8080/api/courses')
    allCourses.value = res.data || []
    filterCourses()
  } catch (e) {
    ElMessage.error('课程获取失败')
  }
}

const initForm = (data) => {
  localForm.id = data?.id ?? null
  localForm.cardName = data?.cardName ?? ''
  localForm.type = getCardLevel(data?.cardName ?? '')
  localForm.price = data?.price ?? ''
  localForm.totalClasses = data?.totalClasses ?? 0
  localForm.remainingClasses = data?.remainingClasses ?? 0
  localForm.description = data?.description ?? ''
  localForm.note = data?.note ?? ''
  filterCourses()
}

watch(
  () => props.memberCardFormData,
  (val) => {
    initForm(val)
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  fetchCourses()
})

const saveMemberCard = () => {
  memberCardForm.value.validate(async (valid) => {
    if (!valid) return
    const payload = { ...localForm }
    try {
      await ElMessageBox.confirm(`确定要${props.drawerTitle}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (payload.id) {
        await axios.put(`http://localhost:8080/api/class-cards/${payload.id}`, payload)
      } else {
        await axios.post(`http://localhost:8080/api/class-cards`, payload)
      }
      ElMessage.success(`${props.drawerTitle}成功`)
      emit('update:addEditDrawer', false)
      emit('saved')
    } catch (err) {
      if (err !== 'cancel') {
        ElMessage.error(`${props.drawerTitle}失败`)
      }
    }
  })
}

const cancel = () => {
  emit('update:addEditDrawer', false)
}

const memberCardForm = ref(null)
</script>

<style scoped lang="less">
.form-card {
  width: 95%;
}
.w50 {
  width: 50%;
}
.form-top {
  border-radius: 5px;
  padding: 10px 5px;
  margin-bottom: 10px;
}
</style>